#include <string.h>
#include "dh_protocol.h"

/// @brief 制作单包
/// @param buf
/// @param comm
/// @param data
void protocol_pack_make(dh_protocol_t *buf, const char *comm, const char *data)
{
    if (buf == NULL)
        return;
    memset(buf, 0, sizeof(dh_protocol_t));
    buf->head0 = DH_PROTOCOL_HEAD;
    buf->head1 = DH_PROTOCOL_HEAD;
    size_t comm_len = strlen(comm);
    comm_len = comm_len > DH_PROTOCOL_COMM_LEN ? DH_PROTOCOL_COMM_LEN : comm_len;
    strncpy(buf->comm, comm, comm_len);

    size_t data_len = strlen(data);
    data_len = data_len > DH_PROTOCOL_COMM_LEN ? DH_PROTOCOL_COMM_LEN : data_len;
    strncpy(buf->data, data, data_len);
    buf->pack_idx = 0;
    buf->pack_count = 1;
    buf->unused = 0;
}

/// @brief 制作分包
/// @param buf 单个包(dh_protocol_t)变量地址
/// @param comm 命令
/// @param data 数据
/// @param cb 回调(通常为发送数据)
/// @param userdata 用户数据
/// @return > -1:参数错误  >0:包数量
int protocol_packs_make(dh_protocol_t *buf, const char *comm, const char *data, protocol_packs_make_cb_impl cb, void *userdata)
{
    if (buf == NULL || comm == NULL || data == NULL)
        return -1;
    memset(buf, 0, sizeof(dh_protocol_t));
    buf->head0 = DH_PROTOCOL_HEAD;
    buf->head1 = DH_PROTOCOL_HEAD;
    size_t comm_len = strlen(comm);
    comm_len = comm_len > DH_PROTOCOL_COMM_LEN ? DH_PROTOCOL_COMM_LEN : comm_len;
    strncpy(buf->comm, comm, comm_len);

    buf->unused = 0;

    size_t data_count_len = strlen(data);
    size_t pack_count = data_count_len / DH_PROTOCOL_DATA_LEN;
    // 如果有剩余的数据，则需要额外的一次分发
    if (data_count_len % DH_PROTOCOL_DATA_LEN != 0)
        pack_count++;

    buf->pack_count = pack_count;

    for (size_t i = 0; i < pack_count; i++)
    {
        strncpy(buf->data, data, data_count_len);
        if (cb != NULL)
            cb(buf, userdata);
    }
    return pack_count;
}